<?php

namespace App\Http\Requests;

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Support\Str;

/**
 * 应用 - 优惠码
 *
 * @Desc:验证请求类
 *
 * @author: zhx
 *
 * @Time: 2023/8/10 10:37
 */
class ApplicationCouponRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * 获取应用于请求的验证规则。
     *
     * @return array<string, \Illuminate\Contracts\Validation\Rule|array|string>
     */
    public function rules(): array
    {
        $r = [
            'name' => 'required|max:50',
            'price' => 'required|max:50',
        ];

        return $r;
    }

    public function messages(): array
    {
        $m = [
            'name.required' => '优惠码名称是必填字段。',
            'price.required' => '优惠码金额是必填字段。',
        ];

        return $m;
    }

    public function all($keys = null)
    {
        $data = parent::all($keys);
        // 在这里排除 _token 字段
        unset($data['_token']);
        unset($data['_method']);

        $data['code'] = md5(Str::uuid());

        return $data;
    }

    protected function failedValidation(Validator $validator)
    {
        $error = $validator->errors()->all();
        throw new HttpResponseException(response()->json(['msg' => $error[0], 'code' => '500', 'data' => 'error'], 500));
    }
}
